import storeList from './components/store-list/store-list.vue';

import {
	request,
	debounce,
	delRepeatJson
} from '@/common/js/util.js';

import {
	pointInPolygon,
	getDistance,
	isOpening
} from '@/common/js/poinInPolygon.js';

export default {
	name: 'Store',
	components: {
		storeList
	},
	data() {
		return {
			storeList: [], // 筛选后的门店列表
			isAuthLocation: true, // 是否授权地理位置
			currentPos: '...', // 根据定位显示的位置
			returnMenu: false, // 返回菜单页 跳转方式为redirectTo
			fromPage: '', // 来源页面
		};
	},
	computed: {
		// 就餐方式
		diningMode() {
			return this.$store.state.diningMode;
		},
		// 所有门店列表
		allStoreList() {
			return this.$store.state.allStoreList;
		},
		// 用户的目标地位点 横纬竖经
		targetPoint() {
			return this.$store.state.targetPoint;
		},
		// 配送地址
		deliveryAddress() {
			return this.$store.state.deliveryAddress;
		}
	},
	watch: {
		targetPoint() {
			this.initData();
		}
	},
	async onLoad(options) {
		this.returnMenu = options.returnMenu || false;
		this.fromPage = options.fromPage || '';
		this.initData();
	},
	methods: {
		// 初始化数据
		async initData() {
			const diningMode = this.diningMode;
			const targetPoint = this.targetPoint;
			const allStoreList = await (this.getAllStoreList() || []);
			const showTestShop = 1 // this.$user.get().showTestShop || 0; // 0不显示，1显示

			if (diningMode === 'wx_zq') {
				let storeList = this.addDistanceOpeing(allStoreList);
				if (targetPoint.x) {
					this.getStreet(targetPoint.y, targetPoint.x);
					let nearStoreList = (storeList.sort((a, b) => a.distance - b.distance)).slice(0, 5);
					if (showTestShop) {
						let testStoreList = storeList.filter(item => item.debug === '1');
						nearStoreList = nearStoreList.concat(testStoreList);
						nearStoreList = delRepeatJson(nearStoreList, 'shopID');
					}
					nearStoreList = this.addAuthNearStatus(nearStoreList);
					this.storeList = nearStoreList;

				} else {
					// 是否显示测试门店
					if (showTestShop) {
						let testStoreList = storeList.filter(item => item.debug === '1');
						testStoreList = this.addAuthNearStatus(testStoreList);
						this.storeList = testStoreList;
						this.currentPos = '未获取到位置';

					} else {
						this.currentPos = '未获取到位置';
						this.isAuthLocation = false;
					}
				}

			} else {

				const deliveryAddress = this.deliveryAddress; // 配送地址
				if (deliveryAddress.latitude !== targetPoint.x) {
					this.$store.commit('handleTargetPoint', {
						x: deliveryAddress.latitude,
						y: deliveryAddress.longitude
					});
				}

				const nearbyStore = deliveryAddress.nearbyStore;
				let areaStoreList = []; // 配送区域门店的门店列表
				allStoreList.map(x => {
					nearbyStore.map(y => {
						if (x.shopID === y) {
							areaStoreList.push(x);
						}
					});
				});

				// 是否显示测试门店
				if (showTestShop) {
					const testStoreList = allStoreList.filter(item => item.debug === '1');
					areaStoreList = areaStoreList.concat(testStoreList);
					areaStoreList = delRepeatJson(areaStoreList, 'shopID');
				}

				areaStoreList = this.addAuthNearStatus(areaStoreList);
				areaStoreList = this.addDistanceOpeing(areaStoreList);
				areaStoreList = areaStoreList.sort((a, b) => {
					let aVal = typeof a.distance === 'number' ? a.distance : 0;
					let bVal = typeof b.distance === 'number' ? b.distance : 0;
					return aVal - bVal;
				});
	
				this.storeList = areaStoreList;
			}

		},

		// 获取所有门店
		async getAllStoreList() {
			if (this.allStoreList && this.allStoreList.length) {
				return this.allStoreList;
			}
			
			uni.showLoading();

			let allStoreList = await request(this.$API.queryAllShop, {}).then(res => {
				return res;
			}).catch(err => {
				return [];
			});
			
			uni.hideLoading();
			
			if (!allStoreList.length) {
				uni.showToast({
					title: '门店列表获取失败',
					icon: 'none',
					duration: 3000
				});
				return;
			}

			allStoreList = allStoreList.filter(item => item.originalBusinessState === '2'); // 只显示营业状态的门店

			// 是否显示测试门店
			const showTestShop = 1; // this.$user.get().showTestShop || 0; // 0不显示，1显示

			// 筛选测试门店
			if (allStoreList.length) {
				if (showTestShop) {
					allStoreList = allStoreList.filter(x => x.name.indexOf('乐凯撒') === -1);
				} else {
					allStoreList = allStoreList.filter(x => (x.name.indexOf('乐凯撒') === -1 && x.debug !== '1'));
				}
			}

			// 缓存所有门店
			this.$store.commit("cacheAllStoreList", allStoreList);

			return allStoreList;
		},

		// 逆向解析定位获取街道
		async getStreet(longitude, latitude) {
			const location = `${latitude},${longitude}`;
			const key = 'SYYBZ-RFT3G-BYTQM-IFQ5V-WNJP7-AVFDN';

			const params = {
				location,
				key
			};

			const street = await request(this.$API.queryGeocoder, params).then(res => {
				const result = res.result.result || '';
				if (result.address_component) {
					return result.address_component.street;
				} else {
					return '逆解析失败'
				}
			}).catch(err => {
				return '';
			});

			this.currentPos = street;
		},


		// 查询定位点对应的附近门店
		queryPointToStore() {
			const targetPoint = this.targetPoint;
			if (targetPoint.x) {
				const params = {
					lng: targetPoint.y,
					lat: targetPoint.x
				};
				request(this.$API.queryUserAreaShop, params).then(res => {
					console.log(res);
				}).catch(err => {
					console.log(err);
				});

			} else {
				this.isAuthLocation = false;
				this.currentPos = '未获取到位置';
			}
		},

		// 添加用户是否授权，是否在附近
		addAuthNearStatus(storeList) {
			if (storeList && storeList.length) {
				const targetPoint = this.targetPoint;
				storeList.map((item, index) => {
					// 是否获取到用户的定位
					if (!targetPoint.x) {
						item.isAuthLocation = false; // 是否授权
						item.isNear = false; // 是否在附近(外卖用) 默认false；注：如果接口返回了用户大概的位置，再做判断
					} else {
						item.isAuthLocation = true;
						const nearbyStore = this.deliveryAddress.nearbyStore || [];
						if (nearbyStore.length) {
							if (nearbyStore.includes(item.shopID) || item.debug === '1') {
								item.isNear = true;
							} else {
								item.isNear = false;
							}
						}

						// 手动判断的位置
						/*
						const serviceArea = item.serviceArea ? item.serviceArea[0] : [];
						const targetPoints = [];
						serviceArea.map(item => {
							targetPoints.push({
								x: item.lat,
								y: item.lng
							})
						})
						const isPoint = serviceArea.length && pointInPolygon(targetPoint, targetPoints);
						item.isNear = isPoint;
						*/
					}
				});
				return storeList;
			} else {
				return []
			}

		},

		// 添加定位距门店距离，营业状态字段和营业时间文本
		addDistanceOpeing(storeList) {
			if (storeList && storeList.length) {
				const targetPoint = this.targetPoint;
				storeList.map(item => {
					const geolocation = item.geolocation;
					const businessHours = item.businessHours;
					let businessHoursText = "";
					if (targetPoint.x) {
						item.distance = getDistance(targetPoint.x, targetPoint.y, geolocation.latitude, geolocation.longitude);
					} else {
						item.distance = "";
					}

					item.openingCategory = isOpening(businessHours);
					businessHours.length && businessHours.map(item => {
						businessHoursText += ` , ${item.from}~${item.to}`;
					})
					businessHoursText = businessHoursText ? businessHoursText.slice(3) : '';
					item.businessHoursText = businessHoursText;
					item.detailAddress = item.city + item.district + item.address;
				})
				return storeList;
			} else {
				return [];
			}
		},

		// 去打开地图选择位置
		onChooseLocation() {
			const that = this;
			uni.chooseLocation({
				success(res) {
					if (res.name === '我的位置') {
						that.getStreet(res.longitude, res.latitude);
					} else {
						that.currentPos = res.name;
					}
					that.$store.commit('handleTargetPoint', {
						x: res.latitude,
						y: res.longitude,
					});
				}
			});
		},

		// 搜索门店
		onConfirmSearch(e) {
			const {
				value
			} = e.detail;

			if (value.trim().length) {
				const allStoreList = this.allStoreList || [];
				let filterStores = allStoreList.filter(item => item.name.indexOf(value) > -1 || item.address.indexOf(value) > -1);

				if (this.diningMode === 'wx_out') {
					const {
						nearbyStore
					} = this.$store.state.deliveryAddress;

					filterStores.map(item => {
						if (nearbyStore.includes(item.shopID) || item.debug === '1') {
							item.isNear = true;
						} else {
							item.isNear = false;
						}
					});
				}
				
				filterStores = this.addDistanceOpeing(filterStores);
				
				filterStores = filterStores.sort((a, b) => {
					let aVal = typeof a.distance === 'number' ? a.distance : 0;
					let bVal = typeof b.distance === 'number' ? b.distance : 0;
					return aVal - bVal;
				});
			
				this.storeList = filterStores;
			}

		},

		// 点击了门店(只执行可下单的)
		onTapStore(store) {
			this.$store.commit('cacheCurrentStoreInfo', store);
			
			if (this.returnMenu) {
				uni.redirectTo({
					url: '/pages/menu/menu'
				})
			} else {
				uni.setStorageSync('isReturnMenu', true);
				if (this.fromPage === 'confirm') {
					uni.navigateBack({delta: 2});
				} else {
					uni.navigateBack();
				}
			}
		
		}
	}
};
